import axios from 'axios'
import { message } from './message'

// hawk 服务所要用到的 BaseURL 
export const service = axios.create({
    // baseURL: 'http://4649xp7900.qicp.vip:57841',
    // baseURL: 'http://localhost:8000/api/',
    
    // baseURL: 'http://4649xp7900.qicp.vip:46836', // 

    baseURL: '/myapi',

    // baseURL: 'http://localhost/myapi',


    // baseURL: 'http://192.168.1.7:8089',

    // baseURL: 'http://192.168.1.7:8090',
    // baseURL: 'http://192.168.0.39:8080',
    // baseURL: 'http://4649xp7900.qicp.vip:57841',
    // baseURL: 'http://4649xp7900.qicp.vip/auth-server',
    // 配置请求超时时间
    timeout: 1000000
})

// const DEBUG = true
const DEBUG = false
var isAuthor = false;
const AuthorBaseURL = '/Authorization';
// const AuthorBaseURL = 'http://localhost/Authorization';

// const AuthorBaseURL = 'http://192.168.1.7:8080/auth-server';
// const AuthorBaseURL = 'http://4649xp7900.qicp.vip';


export async function login (args) {
    isAuthor = true;
    return await postForm(args)
}


/**
 * 退出登陆
 * @param {} token 
 * @returns 
 */
 export async function logOut(token) {
    isAuthor = true;
    return await service({
        url: `/logout?accessToken=${token}`,
        method: 'get'
    })
}


/**
 *  POST  from 表单提交
 * @param {*} args 声明请求的方式  
 * @returns 
 */
export async function postForm (args) {
    let res = await service({
        method: "POST",
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        transformRequest: [
            function (data) {
                let ret = ''
                for (let it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                }
                ret = ret.substring(0, ret.lastIndexOf('&'));
                return ret
            }
        ],
        ...args
    })
    return res
}

/**
 * 发送 json 数据的 请求 
 * @param {*} args 声明请求的方式  
 * @returns 
 */
export async function reqJson (args) {

    const data = await service({
        headers: {
            'Content-Type': 'application/json'
        },
        ...args
    })
    return data
}



const reqConfig = (config) => {
    // 自定义header，可添加项目token
    // config.headers.token = window.sessionStorage.getItem('hawk_token')

    // 如果是认证，改为认证地址
    if (isAuthor) {
        config.headers.Authorization = "Basic aGF3azoxMjM0NTY="
        config.baseURL = AuthorBaseURL
        // config.url = AuthorBaseURL + config.url
        isAuthor = false
        
    } else {
        config.headers.Authorization = "Bearer " + window.sessionStorage.getItem('hawk_token')
    }
    
    
    // console.log(config.url);
    return config
}

// 请求拦截
service.interceptors.request.use(reqConfig)

const resp = (response) => {
    // 获取接口返回结果
    if (DEBUG) {
        console.log("获取接口返回结果");
        console.log(response);
    }
    const res = response.data
    if (res.code === 0) {
        return res
    } else if (res.code === 10000) { // 没登陆 或 token 不对
        // res.msg && message.warning(res.msg)
        message.warning('登陆过期，请重新登陆')
        window.location.href = '/hawk/login'
        return res
    } else if (res.code === 20000) { // 成功
        return res
    } else if (res.code === 998 || res.code == 999) {
        if(res.message == '请登录'){
            window.location.href = '/hawk/login'
            return
        }
        return res
    } else {
        if (res && res['code'] && res.message) {
            console.log(res.message);
            message.warning(res.message)
            return res
        } else {
            return res
        }

    }
}

const netError = (res) => {
    if (String(res).indexOf('401') != -1) {
        // message.warning('登陆过期，请重新登陆')
        window.location.href = '/hawk/login'
    }
    console.warn(String(res),"---网络请求异常");
    if(String(res).indexOf('403') != -1){
        message.error("没有相关权限")
    }
    // message.error('网络请求异常，请稍后重试!')
}

// 返回拦截
service.interceptors.response.use(resp, netError)
